import os
import shutil

from django.conf import settings
from django.db import transaction
from django.shortcuts import render
from rest_framework.parsers import JSONParser
from django.core.files.storage import default_storage
from core.response import CustomResponse,StandardPagination
from file.services import file_service, textvector_service, imagevector_service, knowbase_service
from rest_framework.decorators import action
from rest_framework import viewsets
from rest_framework.permissions import AllowAny
from file.models import File, KnowledgeBase
from file.services.file_service import FileSerializer
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from rest_framework.pagination import PageNumberPagination


class FileViewSet(viewsets.ViewSet):
    permission_classes = [AllowAny]

    # parser_classes = [JSONParser]

    @action(detail=False, methods=['GET'], url_path='list_html', url_name='list_html')
    def get_filelist_by_knowbase_id(self, request):
        knowbase_id = request.query_params.get('knowbase_id')
        knowbase_name = request.query_params.get('knowbase_name')
        if not knowbase_id:
            return CustomResponse.error(message='缺少knowbase_id参数')

        files_data,paginator = file_service.get_files_by_knowbase_id(knowbase_id,request)

        return render(request, 'file/file_list.html', {
            'files': files_data,
            'knowbase_id': knowbase_id,
            'knowbase_name': knowbase_name,
            'paginator': paginator,
            'page_obj': paginator.page  # DRF 的 Page 对象兼容 Django 的 Page
        })


    @action(detail=False, methods=['DELETE'], url_path='delete', url_name='delete')
    def del_file_by_file_id(self, request):
        # 后续需要做的修改是将所有的文件都存在Data目录下
        file_id = request.data.get('file_id')
        file_name = request.data.get('file_name')
        files = file_service.get_file_by_file_id(file_id)
        if (len(files) == 0):
            return CustomResponse.error(message="当前文件查不到，请确认！")
        file_path = files[0].get('file_path')
        directory_path = os.path.dirname(file_path)
        directory_path = os.path.join(settings.MEDIA_ROOT, directory_path)
        if not os.path.exists(directory_path) or not os.path.isdir(directory_path):
            return CustomResponse.error("当前文件不存在！")
        try:
            shutil.rmtree(directory_path)
            with transaction.atomic():
                try:
                    file_service.delete_file_by_file_id(file_id)
                    textvector_service.delete_by_file_id(file_id)
                    imagevector_service.delete_by_file_id(file_id)
                    return CustomResponse.success(message="当前文件已删除！")
                except Exception as e:
                    return CustomResponse.error(message="当前文件删除失败，原因为" + str(e))
        except Exception as e:
            return CustomResponse.error(message="当前文件删除失败，原因为" + str(e))


    @action(detail=False, methods=['POST'], url_path='upload', url_name='upload')
    def file_upload(self, request):
        upload_file = request.FILES.get('upload_file')
        knowbase_name = request.data.get('knowbase_name')
        knowbases = knowbase_service.get_knowbase_by_name(knowbase_name)
        file_name_no_ext = upload_file.name.split('.')[0]
        file_dir = os.path.join(settings.MEDIA_ROOT, knowbase_name, file_name_no_ext)
        full_path = os.path.join(file_dir, upload_file.name)
        os.makedirs(file_dir, exist_ok=True)
        default_storage.save(full_path, upload_file)
        file_inatance = File.objects.create(
            file_name=upload_file.name,
            file_path=os.path.join(knowbase_name, file_name_no_ext, upload_file.name),
            file_type=upload_file.name.split(".")[-1],
            know_base_id=knowbases[0].get('know_base_id'),
        )
        serializer = FileSerializer(file_inatance)
        return CustomResponse.success(message="文件上传成功！",data=serializer.data)
